/**
 * @author ccpalu
 */
function dataStorage(){
	var chromFunctions = false;
	try {
		document.getElementById('file').value = '';
		document.getElementById('submitFile').disabled = true;
		var cnv = document.getElementById('CNV');
		cnv.uploads = cnv.uploads[0].replace(/"/g, '');
		cnv.uploads = cnv.uploads.split('/\N');
		if (cnv.uploads.length == 1) {
			cnv.uploads = cnv.uploads[0].split(' ');
		}
		if (cnv.clinical.upload) {
			clinicalCollection();
			remove_element_by_id("LoadingStatus");
			
		}
		else {
		
		
			var numberOfColumns = document.getElementById('CNV').uploads[0];
			if (numberOfColumns.split('\t').length<5) {
					alert("Your file doesn't have a valid format.\nIt will be removed - check the Documentation for help.");
			}
			else{
				if (document.getElementById('configDiv') == undefined) {
					configOptions();
				}
				else{
					remove_element_by_id('sampleIdSelect');
					remove_element_by_id('sampleChromosomeSelect');
					remove_element_by_id('segmentStartSelect');
					remove_element_by_id('segmentEndSelect');
					remove_element_by_id('copyNumberSelect');
					remove_element_by_id('cnNotationSelect');
					
					remove_element_by_id('sampleIdLabel');
					remove_element_by_id('sampleChromosomeLabel');
					remove_element_by_id('segmentStartLabel');
					remove_element_by_id('segmentEndLabel');
					remove_element_by_id('copyNumberLabel');
					remove_element_by_id('cnNotationLabel');
					
					remove_element_by_id('submitLabels');
					
					graphConfigBox();
				}
					loadingStatus('Waiting user answer');
					createSegLabelForm(numberOfColumns.split('\t'));
			
			}
			
		}
	} 
	catch (error) {
		alert("Your file couldn't be uploaded.\nError: " + error);
		uploadFinished();
	}
	
}

function uploadFinished(chromFunctions){
	if (chromFunctions) {
		chromossomeMetrics();
		createChList();
		
		document.getElementById('choose_sample').disabled = false;
	}
	else{
			remove_element_by_id("LoadingStatus");
	}
	if (document.getElementById('fileUploadForm').style.display == 'none') {
		remove_element_by_id("LoadingStatus");
	}
	if (document.getElementById('filePasteForm').style.display!='none'){
		document.getElementById('pasteText').value='';
	}
	document.getElementById('CNV').uploads.length = 0;
	
	createExportForm();

	return false;	
}


function clinicalCollection()  {
/* ct -
 * lastChr -
 * typeData -
 * segChr - it receives the treated data stored on the
 * 			global varible segData ('getStatements' function)
 * chrm - 
 * 
 * It organize the raw and segmented data received from the S3DB.
 */

	var cnv = document.getElementById('CNV');
	
	var sampSeg = cnv.uploads;
	var segData=cnv.segData;
	if ((sampSeg.length == (cnv.segData[1].length + 1))||((sampSeg.length == (cnv.segData[1].length + 2))&&(sampSeg[sampSeg.length-1]==''))) {
		var ref = cnv.clinical.index, index;
		sampSeg[0] = sampSeg[0].split("\t");
		for (var j = 0; j < sampSeg[0].length; j = j + 1) {
			if (cnv.clinical[sampSeg[0][j]] == undefined) 
				cnv.clinical.labels.push(sampSeg[0][j]);
			cnv.clinical[sampSeg[0][j]] = new Object();
			cnv.clinical[sampSeg[0][j]].original = new Array();
			cnv.clinical[sampSeg[0][j]].color = new Array();
			cnv.clinical[sampSeg[0][j]].category = new Array();
		}
		
		for (var i = 1; i < sampSeg.length; i = i + 1) {
			sampSeg[i] = sampSeg[i].replace(/NaN/g, 'NA');
			sampSeg[i] = sampSeg[i].split("\t");
			
			if (sampSeg[i].length == sampSeg[0].length) {
				index = ref + i - 1;
				for (j = 0; j < sampSeg[i].length; j = j + 1) {
					cnv.clinical[sampSeg[0][j]].original[index] = sampSeg[i][j];
				}
			}
		}
		cnv.clinical.index = i;
		clinicalCategories();
		closeUploadBox();
	}
	else{
		if (!confirm('The file you submited contain a different number of samples.\nYou have ' + 
			cnv.segData[1].length + ' CNV samples.\nWould you like to try again?')) {
			cnv.clinical.upload=false;
			closeUploadBox();
		}
	}
	return false;
}

function clinicalCategories(){
	var clinical = document.getElementById('CNV').clinical;
	var categLength, arrayIndex, isNotNumeric;

	for (var i=0; i< clinical.labels.length; i=i+1){
		isNotNumeric=0;
		for (var j=0; j< clinical[clinical.labels[i]].original.length;j=j+1){
			if ((clinical[clinical.labels[i]].original[j]!='NA')&&(findInArray(clinical[clinical.labels[i]].category,clinical[clinical.labels[i]].original[j])==-1)){
				if (isNaN(clinical[clinical.labels[i]].original[j])) {
					isNotNumeric=1;
				}
				clinical[clinical.labels[i]].category.push(clinical[clinical.labels[i]].original[j]);
			}
		}
		if (isNotNumeric) {
			clinical[clinical.labels[i]].category=clinical[clinical.labels[i]].category.sort();
		}
		else{
			clinical[clinical.labels[i]].category=quickSort(clinical[clinical.labels[i]].category);
		}
	}
	
	for (i=0; i< clinical.labels.length; i=i+1){
		categLength = clinical[clinical.labels[i]].category.length - 1;

		for (j=0; j< clinical[clinical.labels[i]].original.length;j=j+1){
			arrayIndex = findInArray(clinical[clinical.labels[i]].category,clinical[clinical.labels[i]].original[j])*4;
			if (arrayIndex < 0) {
				clinical[clinical.labels[i]].color.push('#FFFFFF');
			}
			else {
				clinical[clinical.labels[i]].color.push(heatMapHexa(arrayIndex / categLength));
			}
		}
	}
	
	return false;
}

function segCollection(labelsSelect)  {
/* ct -
 * lastChr -
 * typeData -
 * segChr - it receives the treated data stored on the
 * 			global varible segData ('getStatements' function)
 * chrm - 
 * 
 * It organize the raw and segmented data received from the S3DB.
 */

	var ct=-1;
	var id='';
	var lastChr='1';
	var cnv = document.getElementById('CNV');
	var sampSeg=new Array;
	var segChrm=new Array;
	var ch=new Array;
	var sampSeg = cnv.uploads;
	var aux='', sexCh = false;
	var segData=cnv.segData;
	var ref = cnv.index;
	var typeChr;
	var selectSample = document.getElementById('choose_sample');
	var mapIndex=cnv.mapAnswer.length;
	
	switch(document.getElementById('cnNotationSelect').selectedIndex ) {
	case 1:
		var base =1;
		var times = 1;
		
		break;
	case 2:
		var base =2;
		var times = 1;
		break;	
	case 3:
		var base =2;
		var times = 2;

	}
	document.getElementById('closeConfigForm').style.display='';
	
	for (var x in sampSeg) {
		try {
			sampSeg[x] = sampSeg[x].split("\t");
			if ((sampSeg[x][labelsSelect[3]].match(/[A-Z]/gi))||(sampSeg[x][labelsSelect[2]].match(/[A-Z]/gi))) {
				//Checking if it has only numbers for segment start and end.
			}
			else {
				if (sampSeg[x][labelsSelect[0]] != id) {
					if (id != '') {
						if (cnv.min[lastChr] > segData[lastChr][cnv.index]['xi'][0]) 
							cnv.min[lastChr] = segData[lastChr][cnv.index]['xi'][0];
						if (cnv.max[lastChr] < segData[lastChr][cnv.index]['xf'][ct]) 
							cnv.max[lastChr] = segData[lastChr][cnv.index]['xf'][ct];
						cnv.index = cnv.index + 1;
						ct = -1;
					}
					id = sampSeg[x][labelsSelect[0]];
					cnv.mapAnswer[mapIndex] = id;
					selectSample.options[selectSample.options.length] = new Option(id, mapIndex);
					mapIndex=mapIndex+1;
					
				}
				try {
					typeChr = sampSeg[x][labelsSelect[1]].match(/\d/g).join("");
					sexCh = false;
				} 
				catch (e) {

					sexCh = true;
				
				}
			if (sexCh)
				continue;
				if (typeChr == lastChr) 
					ct = ct + 1;
				else {
					if (ct >= 0) {
						if (cnv.min[lastChr] > segData[lastChr][cnv.index]['xi'][0]) 
							cnv.min[lastChr] = segData[lastChr][cnv.index]['xi'][0];
						if (cnv.max[lastChr] < segData[lastChr][cnv.index]['xf'][ct]) 
							cnv.max[lastChr] = segData[lastChr][cnv.index]['xf'][ct];
					}
					ct = 0;
				}
				
				if (!segData[typeChr]) 
					segData[typeChr] = new Array;
				
				if (!segData[typeChr][cnv.index]) 
					segData[typeChr][cnv.index] = new Object;
				
				if (!segData[typeChr][cnv.index]['xi']) {
					segData[typeChr][cnv.index]['xi'] = new Array;
					segData[typeChr][cnv.index]['xf'] = new Array;
					segData[typeChr][cnv.index]['y'] = new Array;
					segData[typeChr][cnv.index]['color'] = new Array;
				}
				
				segData[typeChr][cnv.index]['xi'][ct] = sampSeg[x][labelsSelect[2]] * 1;
				segData[typeChr][cnv.index]['xf'][ct] = sampSeg[x][labelsSelect[3]] * 1;
				if (sampSeg[x][labelsSelect[4]].match(/[e]/)) {
					var expAux = sampSeg[x][labelsSelect[4]].match(/[^a-z]{1,}/gi);
					sampSeg[x][labelsSelect[4]] = expAux[0] * Math.pow(Math.E, expAux[1]);
				}
				aux = Math.pow(base, sampSeg[x][labelsSelect[4]])*times;
				segData[typeChr][cnv.index]['y'][ct] = aux;
				segData[typeChr][cnv.index]['color'][ct] = heatMapHexa(aux);//(Math.log(aux+1)/Math.LN2)); //(aux);//
				
				lastChr = typeChr;
			}
		}
		catch (e){
			console.log(e + ' x=' + x + ' id=' + id);
		}
	}
	if (cnv.min[lastChr]>segData[lastChr][cnv.index]['xi'][0])
		cnv.min[lastChr]=segData[lastChr][cnv.index]['xi'][0];
	if (cnv.max[lastChr]<segData[lastChr][cnv.index]['xf'][ct])
		cnv.max[lastChr]=segData[lastChr][cnv.index]['xf'][ct];
	
	
	cnv.index=cnv.index+1;
	cnv.segData=segData;
	remove_element_by_id("LoadingStatus");
	remove_element_by_id('segFileOptionsDiv');
	remove_element_by_id('configForm2');

	if (confirm('Would you like to upload Complementary Data?')) {
		cnv.clinical.upload=true;
	}
	else{
		closeUploadBox();
	}
	return false;
}

function segS3db(segData,ref, position)  {
/* ct -
 * lastChr -
 * typeData -
 * segChr - it receives the treated data stored on the
 * 			global varible segData ('getStatements' function)
 * chrm - 
 * 
 * It organize the raw and segmented data received from the S3DB.
 */

	var ct=-1;
	var lastChr='1';
	var sampSeg=new Array;
	var segChrm=new Array;
	var ch=new Array;
//	var s3db = document.getElementById('s3db');
	var cnv = document.getElementById('CNV');
	var aux='';
	//var discreatYvector = new Array();
	sampSeg=segData.split(/%0A/g).slice(0,sampSeg.length-1);
	segData=cnv.segData;
	cnv.dataMap[position]=ref;
	for (var x in sampSeg) {
		sampSeg[x] = sampSeg[x].split(/%09/g);
		typeChr = sampSeg[x][0];
		if (typeChr == lastChr) 
			ct = ct + 1;
		else {
			if(ct>=0){
				if (cnv.min[lastChr]>segData[lastChr][cnv.index]['xi'][0])
					cnv.min[lastChr]=segData[lastChr][cnv.index]['xi'][0];
				if (cnv.max[lastChr]<segData[lastChr][cnv.index]['xf'][ct])
					cnv.max[lastChr]=segData[lastChr][cnv.index]['xf'][ct];
			}
			ct = 0;
		}
		
		if (!segData[typeChr]) 
			segData[typeChr] = new Array;
			
		if (!segData[typeChr][cnv.index]) 
			segData[typeChr][cnv.index] = new Object;
		
		if (!segData[typeChr][cnv.index]['xi']) {
			segData[typeChr][cnv.index]['xi'] = new Array;
			segData[typeChr][cnv.index]['xf'] = new Array;
			segData[typeChr][cnv.index]['y'] = new Array;
			segData[typeChr][cnv.index]['color'] = new Array;
		}
		
		
		segData[typeChr][cnv.index]['xi'][ct] = sampSeg[x][1]*1;
		segData[typeChr][cnv.index]['xf'][ct]= sampSeg[x][2]*1;
		aux = sampSeg[x][3]*1;
		
		segData[typeChr][cnv.index]['y'][ct] = aux;
		segData[typeChr][cnv.index]['color'][ct]=heatMapHexa(aux);//(Math.log(aux+1)/Math.LN2)); //(aux);//
			
		lastChr = typeChr;	
	}
	if (cnv.min[lastChr]>segData[lastChr][cnv.index]['xi'][0])
		cnv.min[lastChr]=segData[lastChr][cnv.index]['xi'][0];
	if (cnv.max[lastChr]<segData[lastChr][cnv.index]['xf'][ct])
		cnv.max[lastChr]=segData[lastChr][cnv.index]['xf'][ct];
	
	cnv.index=cnv.index+1;
	cnv.segData=segData;
	
	if(cnv.dataMap[cnv.dataMap.length-1])
		addUserSample();
		
	return false;
}